
//用户接口

var express = require('express');
var router = express.Router();
// 导入连接数据库key
const pool = require('../MySQLkey/kry');
// 导入加密库
const bcrypt = require('bcrypt');
// 导入工具类
const tools = require('../tool/tool');


/* GET users listing. */
router.get('/', async function(req, res, next) {
let connection;
try {
  connection = await pool.getConnection();

  // 获取查询参数
  const { phone, page = 1, limit = 10, status } = req.query;

  // 验证分页参数
  const pagination = tools.validatePagination(page, limit);

  // 构建查询条件
  let whereConditions = [];
  let params = [];

  if (phone) {
    if (!tools.validatePhone(phone)) {
      return res.status(400).json({
        success: false,
        error: '手机号格式不正确'
      });
    }
    whereConditions.push('phone = ?');
    params.push(phone);
  }

  if (status !== undefined) {
    whereConditions.push('status = ?');
    params.push(parseInt(status));
  }

  // 构建查询语句
  let query = 'SELECT id, nickname, phone, email, avatar, gender, birthday, status, created_at, updated_at FROM `users`';

  if (whereConditions.length > 0) {
    query += ' WHERE ' + whereConditions.join(' AND ');
  }

  // 添加排序和分页
  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  params.push(pagination.limit, pagination.offset);

  // 执行查询
  const [results] = await connection.execute(query, params);

  // 获取总数（用于分页）
  let countQuery = 'SELECT COUNT(*) as total FROM `users`';
  let countParams = [];

  if (whereConditions.length > 0) {
    countQuery += ' WHERE ' + whereConditions.join(' AND ');
    countParams = params.slice(0, -2); // 移除limit和offset参数
  }

  const [countResult] = await connection.execute(countQuery, countParams);
  const total = countResult[0].total;

  tools.handleSuccess(res, {
    users: results,
    pagination: {
      page: pagination.page,
      limit: pagination.limit,
      total,
      totalPages: Math.ceil(total / pagination.limit)
    }
  }, '用户列表获取成功');

} catch (err) {
  tools.handleError(res, err, '获取用户列表失败');
} finally {
  if (connection) connection.release();
}
});

/* POST user login */
router.post('/login', async function(req, res) {
let connection;
try {
  connection = await pool.getConnection();

  const { phone, password } = req.body;

  // 验证必填字段
  if (!phone || !password) {
    return res.status(400).json({
      success: false,
      error: '手机号和密码为必填项'
    });
  }

  // 验证手机号格式
  if (!tools.validatePhone(phone)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的手机号码'
    });
  }

  // 查询用户（包含密码用于验证）
  const [results] = await connection.execute(
    'SELECT id, nickname, password, phone, email, avatar, gender, birthday, status, created_at, updated_at FROM `users` WHERE `phone` = ? AND status != 0',
    [phone]
  );

  if (results.length === 0) {
    return res.status(401).json({
      success: false,
      error: '手机号或密码错误'
    });
  }

  const user = results[0];

  // 验证密码
  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) {
    return res.status(401).json({
      success: false,
      error: '手机号或密码错误'
    });
  }

  // 记录登录日志（可选）
  try {
    const clientIP = req.ip || req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'unknown';
    await connection.execute(
      'INSERT INTO `user_login_logs` (user_id, login_time, ip_address, user_agent) VALUES (?, NOW(), ?, ?)',
      [user.id, clientIP, req.get('User-Agent') || '']
    );
  } catch (logErr) {
    console.warn('登录日志记录失败:', logErr);
    // 不影响登录流程
  }

  // 移除密码字段，返回用户信息
  const { password: _, ...userInfo } = user;

  tools.handleSuccess(res, {
    user: userInfo,
    message: '登录成功',
    loginTime: new Date().toISOString()
  }, '登录成功');

} catch (err) {
  tools.handleError(res, err, '登录失败');
} finally {
  if (connection) connection.release();
}
});

/* GET user by phone number. */
router.get('/phone/:phone', async function(req, res, next) {
let connection;
try {
  connection = await pool.getConnection();

  const { phone } = req.params;

  // 验证手机号格式
  if (!tools.validatePhone(phone)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的手机号码'
    });
  }

  // 查询用户（排除敏感信息）
  const [results] = await connection.execute(
    'SELECT id, nickname, phone, email, avatar, gender, birthday, status, created_at, updated_at FROM `users` WHERE `phone` = ? AND status != 0',
    [phone]
  );

  if (results.length === 0) {
    return res.status(404).json({
      success: false,
      error: '未找到该手机号对应的用户'
    });
  }

  tools.handleSuccess(res, results[0], '用户信息获取成功');

} catch (err) {
  tools.handleError(res, err, '获取用户信息失败');
} finally {
  if (connection) connection.release();
}
});

/* POST create a new user. */
router.post('/', async function(req, res, next) {
let connection;
try {
  connection = await pool.getConnection();

  const { nickname, phone, email, password, avatar, gender, birthday } = req.body;

  // 如果avatar是上传的图片URL，验证格式
  if (avatar && !avatar.startsWith('/uploads/images/') && !avatar.startsWith('http')) {
    return res.status(400).json({
      success: false,
      error: '头像必须是有效的图片URL'
    });
  }

  // 数据清理
  const cleanNickname = tools.sanitizeString(nickname);
  const cleanPhone = tools.sanitizeString(phone);
  const cleanEmail = tools.sanitizeString(email);

  // 验证必填字段
  if (!cleanNickname || !cleanPhone || !password?.trim()) {
    return res.status(400).json({
      success: false,
      error: '昵称、手机号和密码为必填项'
    });
  }

  // 验证数据格式
  if (!tools.validatePhone(cleanPhone)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的手机号码'
    });
  }

  if (cleanEmail && !tools.validateEmail(cleanEmail)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的邮箱地址'
    });
  }

  // 验证密码强度
  const passwordValidation = tools.validatePassword(password);
  if (!passwordValidation.valid) {
    return res.status(400).json({
      success: false,
      error: passwordValidation.message
    });
  }

  // 检查手机号是否已存在
  const [existingUsers] = await connection.execute(
    'SELECT id FROM `users` WHERE `phone` = ?', [cleanPhone]
  );

  if (existingUsers.length > 0) {
    return res.status(409).json({
      success: false,
      error: '该手机号已被注册'
    });
  }

  // 加密密码
  const saltRounds = 10;
  const hashedPassword = await bcrypt.hash(password, saltRounds);

  // 插入新用户
  const [result] = await connection.execute(
    'INSERT INTO `users` (nickname, phone, email, password, avatar, gender, birthday, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())',
    [
      cleanNickname,
      cleanPhone,
      cleanEmail,
      hashedPassword,
      tools.sanitizeString(avatar),
      tools.sanitizeString(gender),
      birthday || null
    ]
  );

  tools.handleSuccess(res, {
    userId: result.insertId,
    nickname: cleanNickname,
    phone: cleanPhone
  }, '用户创建成功', 200);

} catch (err) {
  tools.handleError(res, err, '创建用户失败');
} finally {
  if (connection) connection.release();
}
});

/* put update a user. */
router.put('/:id', async function(req, res, next) {
let connection;
try {
  connection = await pool.getConnection();

  const userId = parseInt(req.params.id);
  const { nickname, phone, email, avatar, gender, birthday, status } = req.body;

  // 验证用户ID
  if (!tools.validateUserId(userId)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的用户ID'
    });
  }

  // 检查用户是否存在
  const [existingUsers] = await connection.execute(
    'SELECT id, nickname FROM `users` WHERE `id` = ? AND status != 0', [userId]
  );

  if (existingUsers.length === 0) {
    return res.status(404).json({
      success: false,
      error: '用户不存在或已被删除'
    });
  }

  // 验证数据格式
  if (phone && !tools.validatePhone(phone)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的手机号码'
    });
  }

  if (email && !tools.validateEmail(email)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的邮箱地址'
    });
  }

  // 如果更新手机号，检查是否与其他用户冲突
  if (phone) {
    const [phoneCheck] = await connection.execute(
      'SELECT id FROM `users` WHERE `phone` = ? AND `id` != ?', [phone, userId]
    );

    if (phoneCheck.length > 0) {
      return res.status(409).json({
        success: false,
        error: '该手机号已被其他用户使用'
      });
    }
  }

  // 构建更新语句
  let updateFields = [];
  let updateValues = [];

  if (tools.sanitizeString(nickname)) {
    updateFields.push('nickname = ?');
    updateValues.push(tools.sanitizeString(nickname));
  }
  if (tools.sanitizeString(phone)) {
    updateFields.push('phone = ?');
    updateValues.push(tools.sanitizeString(phone));
  }
  if (email !== undefined) {
    updateFields.push('email = ?');
    updateValues.push(tools.sanitizeString(email));
  }
  if (avatar !== undefined) {
    updateFields.push('avatar = ?');
    updateValues.push(tools.sanitizeString(avatar));
  }
  if (gender !== undefined) {
    updateFields.push('gender = ?');
    updateValues.push(tools.sanitizeString(gender));
  }
  if (birthday !== undefined) {
    updateFields.push('birthday = ?');
    updateValues.push(birthday || null);
  }
  if (status !== undefined) {
    updateFields.push('status = ?');
    updateValues.push(parseInt(status));
  }

  if (updateFields.length === 0) {
    return res.status(400).json({
      success: false,
      error: '没有提供要更新的字段'
    });
  }

  // 添加更新时间
  updateFields.push('updated_at = NOW()');
  updateValues.push(userId);

  // 执行更新
  const [result] = await connection.execute(
    `UPDATE \`users\` SET ${updateFields.join(', ')} WHERE \`id\` = ?`,
    updateValues
  );

  // 获取更新后的用户信息
  const [updatedUser] = await connection.execute(
    'SELECT id, nickname, phone, email, avatar, gender, birthday, status, updated_at FROM `users` WHERE `id` = ?',
    [userId]
  );

  tools.handleSuccess(res, {
    user: updatedUser[0],
    affectedRows: result.affectedRows
  }, '用户信息更新成功');

} catch (err) {
  tools.handleError(res, err, '更新用户信息失败');
} finally {
  if (connection) connection.release();
}
});

/* POST delete a user. */
router.delete('/:id', async function(req, res, next) {
let connection;
try {
  connection = await pool.getConnection();

  const userId = parseInt(req.params.id);

  // 验证用户ID
  if (!tools.validateUserId(userId)) {
    return res.status(400).json({
      success: false,
      error: '请提供有效的用户ID'
    });
  }

  // 检查用户是否存在且未被删除
  const [existingUsers] = await connection.execute(
    'SELECT id, nickname FROM `users` WHERE `id` = ? AND status != 0', [userId]
  );

  if (existingUsers.length === 0) {
    return res.status(404).json({
      success: false,
      error: '用户不存在或已被删除'
    });
  }

  // 软删除：更新状态为0（禁用）而不是物理删除
  const [result] = await connection.execute(
    'UPDATE `users` SET `status` = 0, `updated_at` = NOW() WHERE `id` = ?',
    [userId]
  );

  // 如果需要物理删除，可以使用以下代码替换上面的软删除
  // const [result] = await connection.execute(
  //   'DELETE FROM `users` WHERE `id` = ?',
  //   [userId]
  // );

  tools.handleSuccess(res, {
    deletedUser: {
      id: existingUsers[0].id,
      nickname: existingUsers[0].nickname
    },
    affectedRows: result.affectedRows
  }, '用户删除成功');

} catch (err) {
  tools.handleError(res, err, '删除用户失败');
} finally {
  if (connection) connection.release();
}
});

module.exports = router;
